package com.atguigu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.product.dao.AttrGroupDao;
import com.atguigu.product.entity.AttrGroupEntity;
import com.atguigu.product.vo.AttrGroupWithAttrsVO;
import com.atguigu.product.service.AttrGroupService;
import com.atguigu.product.service.AttrService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Resource
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        //检索多字段模糊匹配
        String key = (String) params.get("key");
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(key)) {
            //select * from pms_attr_group where catelog_id = ? and (attr_group_id = id or attr_group_name like ?)
            wrapper.and((obj) -> {
                obj.eq(AttrGroupEntity::getAttrGroupId, key)
                        .or().like(AttrGroupEntity::getAttrGroupName, key);
            });
        }
        IPage<AttrGroupEntity> page;
        if (catelogId == 0) {
            page = page(new Query<AttrGroupEntity>().getPage(params), wrapper);
        } else {
            page = page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper.eq(AttrGroupEntity::getCatelogId, catelogId));
        }
        return new PageUtils(page);
    }

    /**
     * 根据分类id查出所有的分组
     *
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVO> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        //查询分组信息
        List<AttrGroupEntity> attrGroupEntities = list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, catelogId));

        //查询所有属性
        return attrGroupEntities.stream().map(attrGroupEntity -> {
            AttrGroupWithAttrsVO attrGroupWithAttrsVO = BeanUtil.copyProperties(attrGroupEntity, AttrGroupWithAttrsVO.class);
            attrGroupWithAttrsVO.setAttrs(attrService.getRelationAttrList(attrGroupEntity.getAttrGroupId()));
            return attrGroupWithAttrsVO;

        }).collect(Collectors.toList());
    }

}